package com.hellpro.lolbox.moment.presenter;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.hellpro.lolbox.factory.MainFragmentFactory;
import com.hellpro.lolbox.R;
import com.hellpro.lolbox.moment.view.IMomentFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * 类描述:
 * 创建人:阿犇
 * 创建时间:2016/10/22
 * 备注:
 */

public class MomentPresenter {

    private IMomentFragment mIMomentFragment;
    private List<Fragment> fragments;
    private RadioButton[] buttons;
    private int currentIndex = 0;

    public MomentPresenter(IMomentFragment iMomentFragment){
        this.mIMomentFragment = iMomentFragment;
    }

    //处理布局的创建以及传递网址
    public void setFragments(){
        fragments = new ArrayList<>();
        final RadioGroup mRg = mIMomentFragment.getRadioGroup();
        buttons = new RadioButton[mRg.getChildCount()];
        for (int i = 0; i < mRg.getChildCount(); i++) {
            buttons[i] = (RadioButton) mRg.getChildAt(i);
            Fragment fragment = MainFragmentFactory.createFragment(i);
            Bundle args = new Bundle();
//            args.putString("url" , url);
            fragment.setArguments(args);
            fragments.add(fragment);
        }
        mRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < mRg.getChildCount(); i++) {
                    if (buttons[i].getId() == checkedId) {
                            switchFragment(i);
                    }
                }
            }
        });
    }
    /**
     * 每个fragment的之间的交换
     *
     * @param
     */
    private void switchFragment(int id) {
        //目标fragment
        Fragment fragment = fragments.get(id);
        //当前fragment
        Fragment fragment1 = fragments.get(currentIndex);
        //开启一个事务
        FragmentTransaction transaction = mIMomentFragment.getMomentFragmentManager().beginTransaction();
        if (fragment.isAdded()) {
            transaction.hide(fragment1).show(fragment);
        } else {
            transaction.hide(fragment1).add(R.id.moment_fl_content, fragment);
        }
        transaction.commit();
        currentIndex = id;
    }


}
